{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 138,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /tmp/tensorflow/mnist/input_data\\train-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting /tmp/tensorflow/mnist/input_data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W1 = tf.Variable(tf.zeros([784, 10]))\n",
    "b1 = tf.Variable(tf.zeros([10]))\n",
    "y= tf.matmul(x, W1) + b1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.GradientDescentOptimizer(0.70).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Train\n",
    "for _ in range(6000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 145,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9223\n"
     ]
    }
   ],
   "source": [
    "  # Test trained model\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                      y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到92%左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至98%以上的准确率。\n",
    "Hint：\n",
    "- 多隐层\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 隐层神经元数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个step就对loss、accuracy等等进行一次输出，这样才能有根据地进行调整"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 146,
   "metadata": {},
   "outputs": [],
   "source": [
    "#预测准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pred_accuracy(logists, gamma, batch_size):\n",
    "    # 把初始化全局变量的操作放在函数中，之后每个不同训练模型不用重复写初始化代码\n",
    "    sess.run(tf.global_variables_initializer())  \n",
    "    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=logists))  \n",
    "    train_step = tf.train.GradientDescentOptimizer(gamma).minimize(cross_entropy) \n",
    "    \n",
    "    for i in range(3000):                                             \n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)                            \n",
    "        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        \n",
    "    correct_prediction = tf.equal(tf.argmax(logists,1), tf.argmax(y_,1))      \n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) \n",
    "    print('accuracy =',sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "多隐层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy = 0.3476\n"
     ]
    }
   ],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W1 = tf.Variable(tf.zeros([784, 392]))\n",
    "b1 = tf.Variable(tf.zeros([392]))\n",
    "logit1= tf.matmul(x, W1) + b1\n",
    "y1=tf.nn.sigmoid(logit1)\n",
    "W2 = tf.Variable(tf.zeros([392, 10]))\n",
    "b2 = tf.Variable(tf.zeros([10]))\n",
    "logit2= tf.matmul(y1, W2) + b2\n",
    "pred_accuracy(logists=logit2, gamma=0.7, batch_size=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "权重初始化方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 149,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "权重初始化：截断正态分布\n",
      "accuracy = 0.9801\n",
      "权重初始化：随机正态分布\n",
      "accuracy = 0.9768\n",
      "权重初始化：随机均匀分布\n",
      "accuracy = 0.337\n"
     ]
    }
   ],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W1_1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))   # 截断正态分布 \n",
    "W1_2 = tf.Variable(tf.random_normal([784,392],stddev=0.05))      # 随机正态分布\n",
    "W1_3 = tf.Variable(tf.random_uniform([784,392]))                 # 随机均匀分布\n",
    "b1 = tf.Variable(tf.zeros([392]))                                # 偏差一般都是初始化为0\n",
    "\n",
    "logist1_1 = tf.matmul(x, W1_1) + b1\n",
    "logist1_2 = tf.matmul(x, W1_2) + b1 \n",
    "logist1_3 = tf.matmul(x, W1_3) + b1 \n",
    "\n",
    "y1_1 = tf.nn.relu(logist1_1)\n",
    "y1_2 = tf.nn.relu(logist1_2)\n",
    "y1_3 = tf.nn.relu(logist1_3)\n",
    "\n",
    "W2_1 = tf.Variable(tf.truncated_normal([392, 10],stddev=0.05)) \n",
    "W2_2 = tf.Variable(tf.random_normal([392, 10],stddev=0.05)) \n",
    "W2_3 = tf.Variable(tf.random_uniform([392, 10])) \n",
    "b2 = tf.Variable(tf.zeros([10]))       \n",
    "\n",
    "logist2_1 = tf.matmul(y1_1, W2_1) + b2\n",
    "logist2_2 = tf.matmul(y1_2, W2_2) + b2 \n",
    "logist2_3 = tf.matmul(y1_3, W2_3) + b2 \n",
    "\n",
    "print(\"权重初始化：截断正态分布\")\n",
    "pred_accuracy(logists=logist2_1, gamma=0.5, batch_size=100)\n",
    "print(\"权重初始化：随机正态分布\")\n",
    "pred_accuracy(logists=logist2_2, gamma=0.5, batch_size=100)\n",
    "print(\"权重初始化：随机均匀分布\")\n",
    "pred_accuracy(logists=logist2_3, gamma=0.5, batch_size=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用截断正态分布初始化变量的准确率高些，初始化方式使用截断正态分布"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "激活函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 152,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy = 0.9809\n",
      "accuracy = 0.962\n",
      "accuracy = 0.9774\n"
     ]
    }
   ],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "W1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))\n",
    "b1 = tf.Variable(tf.zeros([392]))\n",
    "logit1= tf.matmul(x, W1) + b1\n",
    "y1_1=tf.nn.relu(logit1)\n",
    "y1_2=tf.nn.sigmoid(logit1)\n",
    "y1_3=tf.nn.tanh(logit1)\n",
    "W2 = tf.Variable(tf.truncated_normal([392,10],stddev=0.05))\n",
    "b2 = tf.Variable(tf.zeros([10]))\n",
    "y1_n=[y1_1,y1_2,y1_3]\n",
    "for y in y1_n:\n",
    "    logit2= tf.matmul(y, W2) + b2\n",
    "    pred_accuracy(logists=logit2, gamma=0.7, batch_size=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用relu函数有较高准确率，激活函数使用relu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定一个单隐层的神经网络，并进行初始化\n",
    "def one_hidden_layer_init(num_neural):\n",
    "    W1 = tf.Variable(tf.truncated_normal([784,num_neural],stddev=0.05))\n",
    "    b1 = tf.Variable(tf.zeros([num_neural]))                   \n",
    "    logist1 = tf.matmul(x, W1) + b1           \n",
    "    y1 = tf.nn.relu(logist1)                \n",
    "\n",
    "    W2 = tf.Variable(tf.truncated_normal([num_neural, 10],stddev=0.05))   \n",
    "    b2 = tf.Variable(tf.zeros([10]))        \n",
    "    logist2 = tf.matmul(y1, W2) + b2   \n",
    "    \n",
    "    return logist2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "神经元个数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 154,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "num of neural is: 1\n",
      "accuracy = 0.3208\n",
      "num of neural is: 2\n",
      "accuracy = 0.5416\n",
      "num of neural is: 100\n",
      "accuracy = 0.9768\n",
      "num of neural is: 392\n",
      "accuracy = 0.9775\n",
      "num of neural is: 784\n",
      "accuracy = 0.9807\n",
      "num of neural is: 1000\n",
      "accuracy = 0.9823\n",
      "num of neural is: 1500\n",
      "accuracy = 0.9804\n"
     ]
    }
   ],
   "source": [
    "num_neurals = [1,2,100,392,784,1000,1500]\n",
    "for neural in num_neurals:\n",
    "    logist = one_hidden_layer_init(neural)\n",
    "    print(\"num of neural is: %d\" %neural)\n",
    "    pred_accuracy(logists=logist, gamma=0.5, batch_size=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "选取神经元个数392"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "batch_size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "batch = 50:\n",
      "accuracy = 0.9775\n",
      "batch = 100:\n",
      "accuracy = 0.9792\n",
      "batch = 200:\n",
      "accuracy = 0.9813\n",
      "batch = 500:\n",
      "accuracy = 0.9811\n",
      "batch = 1000:\n",
      "accuracy = 0.9804\n",
      "batch = 2000:\n",
      "accuracy = 0.979\n"
     ]
    }
   ],
   "source": [
    "logist = one_hidden_layer_init(num_neural=392)\n",
    "\n",
    "batchs = [50,100,200,500,1000,2000]\n",
    "for batch in batchs:\n",
    "    print(\"batch = %d:\" %batch)\n",
    "    pred_accuracy(logists=logist, gamma=0.5, batch_size=batch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "选取batch 200"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "学习率gamma"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "gamma = 0.010000:\n",
      "accuracy = 0.9143\n",
      "gamma = 0.100000:\n",
      "accuracy = 0.9623\n",
      "gamma = 0.300000:\n",
      "accuracy = 0.9778\n",
      "gamma = 0.600000:\n",
      "accuracy = 0.98\n",
      "gamma = 0.800000:\n",
      "accuracy = 0.9803\n",
      "gamma = 1.000000:\n",
      "accuracy = 0.9816\n",
      "gamma = 5.000000:\n",
      "accuracy = 0.1009\n",
      "gamma = 10.000000:\n",
      "accuracy = 0.0958\n"
     ]
    }
   ],
   "source": [
    "logist = one_hidden_layer_init(num_neural=392)\n",
    "\n",
    "gammas = [0.01,0.1,0.3,0.6,0.8,1,5,10]\n",
    "for gamma0 in gammas:\n",
    "    print(\"gamma = %f:\" %gamma0)\n",
    "    pred_accuracy(logists=logist, gamma=gamma0, batch_size=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "学习率选取1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "隐层数目"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "两个隐层：\n",
      "accuracy = 0.9815\n"
     ]
    }
   ],
   "source": [
    "# 两个隐层\n",
    "W1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))\n",
    "b1 = tf.Variable(tf.zeros([392]))                   \n",
    "logist1 = tf.matmul(x, W1) + b1           \n",
    "y1 = tf.nn.relu(logist1)    \n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([392,392],stddev=0.05))\n",
    "b2 = tf.Variable(tf.zeros([392]))                   \n",
    "logist2 = tf.matmul(y1, W2) + b2          \n",
    "y2 = tf.nn.relu(logist2)  \n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([392, 10],stddev=0.05))   \n",
    "b3 = tf.Variable(tf.zeros([10]))        \n",
    "logist3 = tf.matmul(y2, W3) + b3 \n",
    "\n",
    "print(\"两个隐层：\")\n",
    "pred_accuracy(logists=logist3, gamma=1.0, batch_size=200)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 160,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "三个隐层：\n",
      "accuracy = 0.9726\n"
     ]
    }
   ],
   "source": [
    "# 三个隐层\n",
    "W1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))\n",
    "b1 = tf.Variable(tf.zeros([392]))                   \n",
    "logist1 = tf.matmul(x, W1) + b1           \n",
    "y1 = tf.nn.relu(logist1)    \n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([392,392],stddev=0.05))\n",
    "b2 = tf.Variable(tf.zeros([392]))                   \n",
    "logist2 = tf.matmul(y1, W2) + b2          \n",
    "y2 = tf.nn.relu(logist2)  \n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([392,392],stddev=0.05))\n",
    "b3 = tf.Variable(tf.zeros([392]))                   \n",
    "logist3 = tf.matmul(y2, W3) + b3         \n",
    "y3 = tf.nn.relu(logist3)  \n",
    "\n",
    "W4 = tf.Variable(tf.truncated_normal([392, 10],stddev=0.05))   \n",
    "b4 = tf.Variable(tf.zeros([10]))        \n",
    "logist4 = tf.matmul(y3, W4) + b4 \n",
    "\n",
    "print(\"三个隐层：\")\n",
    "pred_accuracy(logists=logist4, gamma=1.0, batch_size=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "正则化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 163,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pred_nn_regularization(logists,W1,W2,alpha,L):\n",
    "    sess.run(tf.global_variables_initializer()) \n",
    "    \n",
    "    if L=='L1': \n",
    "        #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=logists))\n",
    "        #tf.add_to_collection(\"losses\",cross_entropy)                               \n",
    "        #tf.add_to_collection(\"losses\",tf.contrib.layers.l1_regularizer(0.0001)(W1)) \n",
    "        #tf.add_to_collection(\"losses\",tf.contrib.layers.l1_regularizer(0.0001)(W2)) \n",
    "        #loss = tf.add_n(tf.get_collection(\"losses\")[1:])          \n",
    "        cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=logists)\\\n",
    "                                     +tf.contrib.layers.l1_regularizer(alpha)(W1)\\\n",
    "                                     +tf.contrib.layers.l1_regularizer(alpha)(W2))    \n",
    "        #print(\"L = L1:\")\n",
    "    elif L=='L2':\n",
    "        cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_, logits=logists)\\\n",
    "                                      +tf.contrib.layers.l2_regularizer(alpha)(W1)\\\n",
    "                                      +tf.contrib.layers.l2_regularizer(alpha)(W2)) \n",
    "        #print(\"L = L2:\")\n",
    "    \n",
    "    train_step = tf.train.GradientDescentOptimizer(0.8).minimize(cross_entropy) \n",
    "    for i in range(3000):                                             \n",
    "        batch_xs, batch_ys = mnist.train.next_batch(200)                            \n",
    "        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "        \n",
    "    correct_prediction = tf.equal(tf.argmax(logists,1), tf.argmax(y_,1))      \n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) \n",
    "    print('accuracy =',sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels}))   \n",
    "        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "L1正则"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L1: alpha = 0.000010\n",
      "accuracy = 0.9811\n",
      "L1: alpha = 0.000100\n",
      "accuracy = 0.9768\n",
      "L1: alpha = 0.001000\n",
      "accuracy = 0.844\n",
      "L1: alpha = 0.010000\n",
      "accuracy = 0.2853\n",
      "L1: alpha = 0.100000\n",
      "accuracy = 0.1268\n"
     ]
    }
   ],
   "source": [
    "alphas = [0.00001,0.0001,0.001,0.01,0.1]\n",
    "\n",
    "for alpha in alphas:  \n",
    "    W1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))\n",
    "    b1 = tf.Variable(tf.zeros([392]))                   \n",
    "    logist1 = tf.matmul(x, W1) + b1           \n",
    "    y1 = tf.nn.relu(logist1)                \n",
    "\n",
    "    W2 = tf.Variable(tf.truncated_normal([392, 10],stddev=0.05))   \n",
    "    b2 = tf.Variable(tf.zeros([10]))        \n",
    "    logist2 = tf.matmul(y1, W2) + b2   \n",
    "    \n",
    "    print(\"L1: alpha = %f\" %alpha)\n",
    "    pred_nn_regularization(logists=logist2,W1=W1,W2=W2,alpha=alpha,L='L1')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "L2正则"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 166,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "L1: alpha = 0.000010\n",
      "accuracy = 0.9809\n",
      "L1: alpha = 0.000100\n",
      "accuracy = 0.9672\n",
      "L1: alpha = 0.001000\n",
      "accuracy = 0.8876\n",
      "L1: alpha = 0.010000\n",
      "accuracy = 0.1398\n",
      "L1: alpha = 0.100000\n",
      "accuracy = 0.099\n"
     ]
    }
   ],
   "source": [
    "alphas = [0.00001,0.0001,0.001,0.01,0.1]\n",
    "\n",
    "for alpha in alphas:  \n",
    "    W1 = tf.Variable(tf.truncated_normal([784,392],stddev=0.05))\n",
    "    b1 = tf.Variable(tf.zeros([392]))                   \n",
    "    logist1 = tf.matmul(x, W1) + b1           \n",
    "    y1 = tf.nn.relu(logist1)                \n",
    "\n",
    "    W2 = tf.Variable(tf.truncated_normal([392, 10],stddev=0.05))   \n",
    "    b2 = tf.Variable(tf.zeros([10]))        \n",
    "    logist2 = tf.matmul(y1, W2) + b2   \n",
    "    \n",
    "    print(\"L1: alpha = %f\" %alpha)\n",
    "    pred_nn_regularization(logists=logist2,W1=W1,W2=W2,alpha=alpha,L='L1')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
